package com.df.tv.launcher.model;

import java.util.List;

import android.text.TextUtils;
import android.view.View;

import com.df.tv.launcher.util.JsonParseUtil;
import com.df.tv.launcher.util.XHttpParamsUtil;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.telecom.tv189.comlib.models.LogBatchSendExecutor.FlushExecutor;
import com.telecom.tv189.comlib.models.LogSender.LogData;
import com.telecom.tv189.comlib.net.XHttpClient;
import com.telecom.tv189.comlib.net.json.entity.BaseEntity;
import com.telecom.tv189.comlib.util.Log;
import com.telecom.tv189.silentlogin.UserInfo;
import com.telecom.tv189.silentlogin.UserInfoKeeper;

public class ClickLogFlushExecutor implements FlushExecutor<View, String, String> {

    private static final String TAG = "ClickLogFlushExecutor";

    private static final int ACTION_USER_BEHAVIOR = 3;
    private static final int CODE_OTHER = 0;

    public ClickLogFlushExecutor() {}

    @Override
    public boolean flush(List<LogData<View, String, String>> logs) {
        Log.i(TAG, "click log flush");
        try {
            StringBuffer sb = new StringBuffer();
            for (LogData<View, String, String> log : logs) {
                if (TextUtils.isEmpty(log.action))
                    break;
                sb.append(log.getTimeStamp() + "," + log.action + "|");
            }
            String msg = sb.toString();
            if (!TextUtils.isEmpty(msg)) {
                XHttpClient client = XHttpClient.getInstance();
                XHttpParamsUtil paramsUtil = XHttpParamsUtil.getInstance();
                JsonParseUtil parseUtil = JsonParseUtil.getInstance();

                UserInfo info = UserInfoKeeper.getInstance().getInfo();
                if (!TextUtils.isEmpty(info.getToken())) {
                    ResponseInfo<String> result = client.postSync(
                            paramsUtil.tmsUpdateLog(info.getToken(), ACTION_USER_BEHAVIOR, CODE_OTHER, msg), null);
                    Log.i(TAG, result.result);
                    BaseEntity<Object> res = parseUtil.tmsUpdateLog(result.result);
                    switch (res.getCode()) {
                    case 0:
                        // ok
                        return true;
                    }
                }
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // fail
        return true;
    }
}
